const getClass = require('../../lib/getClass'),
  log = require('./log')

exports.getUrl = obj => {
  obj = obj || {}
  var promise = new Promise((resolve, reject) => {
    if (!obj.url) {
      reject()
      return
    }
    const urlObj = require('url').parse(obj.url, true);
    var options = {
      host: urlObj.hostname,
      port: urlObj.port,
      path: urlObj.pathname + (urlObj.search ? urlObj.search : ''),
      method: 'GET',
    }
    const req = (urlObj.protocol == 'https:' ? require('https') : require('http')).request(options, (res) => {
      if (res.statusCode == 301 || res.statusCode == 302) {
        obj.url = res.headers.location
        log(obj.url)
        exports.getUrl(obj).then(result => {
          resolve(result)
        }, result => {
          reject(result)
        })
        return
      }
      if (res.statusCode == 200) {
        var body = []
        res.on('data', (chunk) => {
          body.push(chunk)
        }).on('end', () => {
          var html = Buffer.concat(body).toString()
          var start = html.indexOf('<meta http-equiv="refresh"')
          if (start != -1) {
            start = html.indexOf('URL=', start) + 4
            var url = html.substring(start, html.indexOf('"', start))
            obj.url = decodeURIComponent(url)
            log(obj.url)
            exports.getUrl(obj).then(result => {
              resolve(result)
            }, result => {
              reject(result)
            })
            return
          }
          resolve(obj.url)
        })
      }
    }).on('error', (err) => {
      reject(err)
    })
    req.end()
  })
  return promise
}
